var checkUrl = "http://192.168.62.106:8080/newVersion?updateType="; //版本检测
//updateType=1 整包更新
//updateType=2 应用资源升级
//updateType=3 应用资源差量升级

/**
 * 更新
 */
function appUpdate(curVer, updateType) {
	var xhr = new plus.net.XMLHttpRequest();
	xhr.onreadystatechange = function() {
		switch(xhr.readyState) {
			case 0:
				console.log("xhr请求已初始化");
				break;
			case 1:
				console.log("xhr请求已打开");
				break;
			case 2:
				console.log("xhr请求已发送");
				break;
			case 3:
				console.log("xhr请求已响应");
				break;
			case 4:
				if(xhr.status == 200) {
					console.log("检测更新成功：" + xhr.responseText);
					var newVer = JSON.parse(xhr.responseText).android.version;
					var downloadUrl = JSON.parse(xhr.responseText).android.url;
					if(curVer && newVer && (curVer != newVer)) {
						download(downloadUrl); //下载升级包
					} else {
						plus.nativeUI.alert("无新版本可更新！");
					}
				} else {
					console.log("检测更新失败！");
					plus.nativeUI.alert("检测更新失败！");
				}
				break;
			default:
				break;
		}
	}
	xhr.open('GET', checkUrl + updateType + "&curVer=" + curVer);
	xhr.send();

}

/**
 * 下载
 * @param {Object} url
 */
function download(url) {
	var dtask = plus.downloader.createDownload(url, {}, function(d, status) {
		if(status == 200) { // 下载成功
			var path = d.filename;
			console.log(path);
			install(path);
		} else { //下载失败
			console.log("Download failed: " + status);
		}
	});
	dtask.start();
}

/**
 * 安装[整包升级、应用资源升级、应用资源差量升级]
 * @param {Object} path
 */
function install(path) {
	plus.runtime.install(path, {}, function() {
		console.log("安装成功！");
		plus.runtime.restart();
	}, function(e) {
		console.log("安装失败");
	});
}

/**
 * 比较版本大小，如果新版本nv大于旧版本ov则返回true，否则返回false
 * @param {String} ov
 * @param {String} nv
 * @return {Boolean} 
 */
function compareVersion( ov, nv ){
	if ( !ov || !nv || ov=="" || nv=="" ){
		return false;
	}
	var b=false,
	ova = ov.split(".",4),
	nva = nv.split(".",4);
	for ( var i=0; i<ova.length&&i<nva.length; i++ ) {
		var so=ova[i],no=parseInt(so),sn=nva[i],nn=parseInt(sn);
		if ( nn>no || sn.length>so.length  ) {
			return true;
		} else if ( nn<no ) {
			return false;
		}
	}
	if ( nva.length>ova.length && 0==nv.indexOf(ov) ) {
		return true;
	}
}
